package jupiter.servlets;

import java.io.IOException;
import java.net.URLEncoder;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import jupiter.filters.UserFilter;
import jupiter.messaging.Inbox;
import jupiter.messaging.Message;
import jupiter.util.Timey;

import org.json.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MessageServlet extends HttpServlet {
	Logger logger = LoggerFactory.getLogger(MessageServlet.class);
	public void service(HttpServletRequest req, HttpServletResponse res) throws java.io.IOException {
		try{
			logger.info("starting a request to MessageServlet");
			String mes = req.getParameter("data");
			if(mes == null){
				res.setContentType("text/javascript; charset=utf-8");
				res.getWriter().print("ERROR: There is no data in your Jabbify Message.");
				res.getWriter().flush();
				return;
			}
			Timey t = new Timey();
			logger.warn("new Message: "+mes.toString());
			
			HttpSession session = req.getSession(false);
			Message message;
			if(session == null){
				message = new Message(mes, req );
			}else{
				Inbox i = (Inbox) session.getAttribute("Inbox");
				message = new Message(mes, i , req );
			}
			logger.info("***Message: "+message.toString());
			JSONObject j = message.send();
			if(message.is_registered == false){
				this.register(message, req, res);
				return;
			}
			String result;
			if(j == null){
				result = mes;
			}else{
				result = j.toString();
			}
			logger.info("***result: "+result.toString());
	
			String callback = req.getParameter("callback");
			String nocallback = req.getParameter("nocallback");
			if(nocallback == null){
				res.setContentType("text/javascript; charset=utf-8");
				res.getWriter().print(callback+"("+result+")");
			}
			else{
				res.setContentType("text/plain");
				res.getWriter().print(result);
			}
		    res.getWriter().flush();
		    
			t.end("Message");
		}catch(RuntimeException e){
			logger.error("RuntimeException in MessageServlet", e);
			throw e;
	    }catch(Exception e){
			logger.error("Exception in MessageServlet", e);
	    }
	}
	
	public void register(Message m, HttpServletRequest req, HttpServletResponse res) throws IOException{
		res.setContentType("text/javascript");
		String host = System.getProperty("HOSTNAME");
		logger.info("host: "+host);
		String redirect;
			if(host == null)
				redirect = "include(\"https://127.0.0.1/clients/register.js\")";
			else if (host.indexOf("moschelrules.com") != -1)
				redirect = "include(\"https://moschelrules.com/clients/register.js\")";
			else
				redirect = "include(\"https://jabbify.com/clients/register.js\")";
			String callback = req.getParameter("callback");
			String nocallback = req.getParameter("nocallback");
			if(nocallback == null){
				res.getWriter().print(callback+"();"+redirect);
			}
		    res.getWriter().flush();
	}
	
	static public String wrap(String data){
		StringBuffer sb = new StringBuffer();
		sb.append("<html>\n");
		sb.append("<script type='text/javascript'>\n");
		sb.append("window.name = document.getElementsByTagName('script')[0]\n");
		sb.append(".innerHTML.match(/temp\\s*=([\\w\\W]*)/)[1];\n");
		sb.append("temp=");
		sb.append(data);
		sb.append("\n");
		sb.append("</script>");
		sb.append("</html>");
		return sb.toString();
	}
	
}
